/*
 * Copyright (c) 2018.
 * http://www.ulabcare.com
 */

package com.mt.roll.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.roll.core.api.Assert;
import com.mt.roll.core.base.BaseService;
import com.mt.roll.core.dal.entity.SysOrg;
import com.mt.roll.core.dal.entity.SysUser;
import com.mt.roll.core.dal.service.SysOrgServiceBiz;
import com.mt.roll.core.dal.service.SysUserServiceBiz;
import com.mt.roll.core.dto.LoginUser;
import com.mt.roll.core.dto.Permission;
import com.mt.roll.core.enums.WhetherEnum;
import com.mt.roll.core.errorcode.ApiErrorCode;
import com.mt.roll.core.utils.PasswordUtil;
import com.mt.roll.core.utils.TreeUtil;
import com.mt.roll.core.vo.LoginUserVo;
import com.mt.roll.core.vo.R;
import com.mt.roll.core.vo.UserMenuVo;
import com.mt.roll.upms.mapper.MenuMapper;
import com.mt.roll.upms.mapper.ResourceMapper;
import com.mt.roll.upms.service.UpmsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用权限服务实现类
 *
 * @author jiff
 * @date 2018-11-27
 * @since 1.0
 */
@Service
@Transactional
public class UpmsServiceImpl extends BaseService implements UpmsService {
    private final SysUserServiceBiz sysUserServiceBiz;
    private final SysOrgServiceBiz sysOrgServiceBiz;
    private final MenuMapper menuMapper;
    private final ResourceMapper resourceMapper;

    @Autowired
    public UpmsServiceImpl(SysUserServiceBiz sysUserServiceBiz, SysOrgServiceBiz sysOrgServiceBiz, MenuMapper menuMapper, ResourceMapper resourceMapper) {
        this.sysUserServiceBiz = sysUserServiceBiz;
        this.sysOrgServiceBiz = sysOrgServiceBiz;
        this.menuMapper = menuMapper;
        this.resourceMapper = resourceMapper;
    }

    /**
     * 用户登录
     *
     * @param mobile   手机号码
     * @param password 密码
     * @return 登录用户
     */
    @Override
    public R<LoginUser> login(String mobile, String password) {
        Assert.notNull(ApiErrorCode.INVALID_PARAMETER, mobile, password);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq(SysUser.MOBILE, mobile);
        SysUser user = sysUserServiceBiz.getOne(wrapper);
        if (user == null) {
            return failed(ApiErrorCode.USER_NON_EXISTENT);
        }
        if (WhetherEnum.NO.getValue().equals(user.getEnabled())) {
            return failed(ApiErrorCode.USER_DISABLED);
        }
        String userPassword = user.getPassword();
        if (userPassword.equals(PasswordUtil.encode(password, user.getNonceStr()))) {
            return successful(LoginUser.builder()
                    .userId(user.getId()).mobile(user.getMobile()).userName(user.getName())
                    .orgId(user.getOrgId())
                    .userType(LoginUser.USER_TYPE_PLATFORM).build());
        }
        return failed(ApiErrorCode.USER_NON_EXISTENT_OR_INVALID_PASSWORD);
    }

    /**
     * 退出登录
     *
     * @return 处理结果
     */
    @Override
    public R<Serializable> logout() {
        return successful(null);
    }

    /**
     * 获取登录用户信息
     *
     * @param mobile 手机号码
     * @return 登录用户
     */
    @Override
    public R<LoginUser> getLoginUser(String mobile) {
        Assert.notNull(ApiErrorCode.INVALID_PARAMETER, mobile);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq(SysUser.MOBILE, mobile);
        SysUser user = sysUserServiceBiz.getOne(wrapper);
        if (user == null) {
            return failed(ApiErrorCode.USER_NON_EXISTENT);
        }
        if (WhetherEnum.NO.getValue().equals(user.getEnabled())) {
            return failed(ApiErrorCode.USER_DISABLED);
        }
        return successful(LoginUser.builder()
                .userId(user.getId()).mobile(user.getMobile()).userName(user.getName())
                .orgId(user.getOrgId())
                .userType(LoginUser.USER_TYPE_PLATFORM).build());
    }

    /**
     * 获取登录用户信息
     *
     * @return 登录用户
     */
    @Override
    public R<LoginUserVo> getLoginUserVo() {
        LoginUser loginUser = getLoginUser();
        LoginUserVo loginUserVo = LoginUserVo.builder().build();
        BeanUtils.copyProperties(loginUser, loginUserVo);
        SysOrg org = sysOrgServiceBiz.getById(loginUser.getOrgId());
        if (org != null) {
            loginUserVo.setOrgName(org.getName());
        }
        List<UserMenuVo> userMenuVos = menuMapper.listByUser(loginUser.getUserId(), loginUser.getAppType());
        loginUserVo.setMenus(TreeUtil.toTree(userMenuVos));
        return successful(loginUserVo);
    }

    /**
     * 获取用户权限列表
     *
     * @return 权限列表
     */
    @Override
    public List<Permission> getPermissions() {
        //TODO  后续完善权限数据
        LoginUser loginUser = getLoginUser();
        List<Permission> permissions = new ArrayList<>();
        permissions.add(Permission.builder().url("/**").method(HttpMethod.GET.name()).build());
        permissions.add(Permission.builder().url("/**").method(HttpMethod.POST.name()).build());
//        List<Permission> permissions1 = resourceMapper.listByUser(loginUser.getUserId(), loginUser.getAppType());
        return permissions;
    }
}
